<script setup lang="ts">
defineOptions({
  name: "fabBoardWater"
});

import { ref, nextTick, inject, onMounted, getCurrentInstance } from "vue";
import { PxMessageBox } from "px-ui";
import fabBoardModelBox from "../fabBoardModelBox.vue";
import fabBoardEchartsModelBoxItem from "../fabBoardEchartsModelBoxItem.vue";
import { spcquerySpcAnalysis } from "@/api/spc";
import { getFabBoardPieData, getFabBoardBarData, getFabBoardEffluentData, getFabBoardSelectOptions } from "@/api/modules/fab";
import dayjs from "dayjs";

const { proxy }: any = getCurrentInstance();

const configOptions = inject("configOptions", ref<Array<any>>([]));
const emitBoardAreaEventCb = inject("emitBoardAreaEvent") as Function;
const area = inject("area", ref<string>(""));
const module_height = inject("moduleHeight", ref<string>(""));

const effluent = ref<string>("");
const loading = ref<boolean>(false);
const target = ref<string>("");
const target_2 = ref<string>("");
const target_3 = ref<string>("");
const target_4 = ref<string>("");
const effluentOptions = ref<Array<any>>([]);
const barMaterialCode2 = ref<string>("");
const barAreaCode = ref<string>("");
const params = ref<Record<string, any> | null>(null);

const waterConsumptionAreaRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const waterConsumptionFabRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const waterLSRRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const waterPressureRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const waterEffluentRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);

const waterConsumptionAreaData = ref<Record<string, any> | null>(null);
const waterConsumptionFabData = ref<Record<string, any> | null>(null);
const waterLSRData = ref<Record<string, any> | null>(null);
const waterPressureData = ref<Record<string, any> | null>(null);
const waterEffluentData = ref<Record<string, any> | null>(null);

const waterConsumptionAreaTitle = ref<string>("今日纯水用量区域占比");
const waterConsumptionAreaDialogTitle = ref<string>("今日机台纯水用量区域统计（m³）");
const waterConsumptionFabTitle = ref<string>("机台纯水用量统计");
const waterLSRTitle = ref<string>("机台LSR用量统计");
const waterPressureTitle = ref<string>("纯水压力");
const waterEffluentTitle = ref<string>("废液排放量统计");

const waterConsumptionAreaUnit = ref<string>("m³");
const waterConsumptionFabUnit = ref<string>("m³");
const waterLSRUnit = ref<string>("m³");
// const waterPressureUnit = ref<string>("Pa");
const waterEffluentUnit = ref<string>("m³");

const mapConfigOptionsFn = (val: string) => {
  const c = configOptions.value.find(item => item.className === "WATER" && item.chartType === "pie");
  const d = configOptions.value.find(item => item.className === "WATER" && item.chartType === "column" && item.areaId === val);
  const e = configOptions.value.find(
    item => item.className === "WATER" && item.chartType === "spc" && item.areaId === val && item.sign === "纯水压力"
  );
  const f = configOptions.value.find(
    item => item.className === "WATER" && item.chartType === "spc" && item.areaId === val && item.systemId === effluent.value
  );
  target.value = c?.quotaCode;
  target_2.value = d?.quotaCode;
  target_3.value = e?.quotaCode;
  target_4.value = f?.quotaCode;
  return [!e];
};

const areaChangeHandler = async (val: string, flag: boolean = false) => {
  emitBoardAreaEventCb("water", val);
  waterConsumptionAreaData.value = null;
  waterConsumptionFabData.value = null;
  waterPressureData.value = null;
  waterEffluentData.value = null;
  const [flag2] = mapConfigOptionsFn(val);
  barAreaCode.value = area.value === "ALL" ? null : area.value;
  await init(flag, flag2);
};

const effluentChangeHandler = async (val: string) => {
  waterEffluentData.value = null;
  mapConfigOptionsFn(val);
  await queryLineDataFn2();
  await nextTick();
  waterEffluentRef.value.init(false);
};

const startLoading = () => {
  loading.value = true;
};

const closeLoading = () => {
  loading.value = false;
};

// 请求饼图数据
const queryPieDataFn = async (cb?: () => void) => {
  if (!target.value) {
    cb && cb();
    return;
  }
  const params = { materialCode: target.value };
  waterConsumptionAreaRef.value.loading = true;
  const res = await getFabBoardPieData(params, () => {
    closeLoading();
    waterConsumptionAreaRef.value.loading = false;
  });
  waterConsumptionAreaData.value = res;
  cb && cb();
};

// 请求柱状图数据（机台纯水用量统计）
const queryBarDataFn = async (cb?: () => void) => {
  if (!target_2.value) {
    cb && cb();
    return;
  }
  const areaCode = area.value === "ALL" ? null : area.value;
  const params = { materialCode: target_2.value, areaCode };
  waterConsumptionFabRef.value.loading = true;
  const res = await getFabBoardBarData(params, () => {
    closeLoading();
    waterConsumptionFabRef.value.loading = false;
  });
  waterConsumptionFabData.value = res;
  cb && cb();
};

// 请求柱状图数据（机台LSR用量统计）
const queryBarDataFn2 = async (cb?: () => void) => {
  // if (!target_2.value) {
  //   cb && cb();
  //   return;
  // }
  // LSR materialCode 写死为WT01WS01AV021
  barMaterialCode2.value = "WT01WS01AV021";
  const areaCode = area.value === "ALL" ? null : area.value;
  const params = { materialCode: "WT01WS01AV021", areaCode };
  waterLSRRef.value.loading = true;
  const res = await getFabBoardBarData(params, () => {
    closeLoading();
    waterLSRRef.value.loading = false;
  });
  waterLSRData.value = res;
  cb && cb();
};

const exportDataHandler = () => {
  proxy.download("get", "/fab/api/v1/board/eqp/24/emsSpec/export", { ...params.value });
  PxMessageBox.alert("正在导出数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "导出数据", {
    confirmButtonText: "我知道了"
  });
};

const getLineParams = () => {
  const startTime = dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss");
  const endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const timePeriod = "minutes";
  // 调试
  // const timePeriod = "hour";
  const jobIdList = null;
  const pointList = [target_3.value];
  return { startTime, endTime, timePeriod, jobIdList, pointList };
};

const getLineParams2 = () => {
  const areaCode = area.value === "ALL" ? null : area.value;
  const materialCode = target_4.value || null;
  const systemId = effluent.value || null;
  params.value = { areaCode, materialCode, systemId };
};

// 请求折现图数据
const queryLineDataFn = async (cb?: () => void) => {
  const params = getLineParams();
  waterPressureRef.value.loading = true;
  const res = await spcquerySpcAnalysis(params, () => {
    closeLoading();
    waterPressureRef.value.loading = false;
  });
  waterPressureData.value = res.find(item => item.point === target_3.value);
  cb && cb();
};

// 请求折现图数据2
const queryLineDataFn2 = async (cb?: () => void) => {
  getLineParams2();
  waterEffluentRef.value.loading = true;
  const res2 = await getFabBoardEffluentData({ ...params.value }, () => {
    closeLoading();
    waterEffluentRef.value.loading = false;
  });
  waterEffluentData.value = res2;
  cb && cb();
};

const querySelectOptionsFn = async () => {
  const params = { className: "WATER" };
  const res = await getFabBoardSelectOptions(params);
  effluentOptions.value = res.map((item: any) => ({ ...item, value: item.systemId, label: item.systemName }));
  effluentOptions.value.unshift({ value: "", label: "全部废液" });
};

const init = async (flag: boolean = false, flag2: boolean = false) => {
  startLoading();
  queryPieDataFn(async () => {
    await nextTick();
    waterConsumptionAreaRef.value?.init(flag);
  });
  queryBarDataFn(async () => {
    await nextTick();
    waterConsumptionFabRef.value?.init(flag);
  });

  queryBarDataFn2(async () => {
    await nextTick();
    waterLSRRef.value?.init(flag);
  });

  if (!flag2) {
    // queryLineDataFn(async () => {
    //   await nextTick();
    //   waterPressureRef.value.init(flag);
    // });
  } else {
    // await nextTick();
    // waterPressureRef.value.init(flag);
  }
  queryLineDataFn2(async () => {
    await nextTick();
    waterEffluentRef.value?.init(flag);
  });
  closeLoading();
};

onMounted(async () => {
  await querySelectOptionsFn();
});

defineExpose({
  areaChangeHandler
});
</script>

<template>
  <div class="water-content">
    <fabBoardEchartsModelBoxItem
      ref="waterConsumptionAreaRef"
      exportImage
      echartsType="pie"
      eventType="areaCodePie"
      :materialCode="target"
      :dialogTitle="waterConsumptionAreaDialogTitle"
      :title="waterConsumptionAreaTitle"
      :unit="waterConsumptionAreaUnit"
      :data="waterConsumptionAreaData"
    />
    <fabBoardEchartsModelBoxItem
      ref="waterConsumptionFabRef"
      exportImage
      echartsType="bar"
      :materialCode="target_2"
      :areaCode="barAreaCode"
      :title="waterConsumptionFabTitle"
      :unit="waterConsumptionFabUnit"
      :data="waterConsumptionFabData"
    />
    <fabBoardEchartsModelBoxItem
      ref="waterLSRRef"
      exportImage
      echartsType="bar"
      :materialCode="barMaterialCode2"
      :areaCode="barAreaCode"
      :title="waterLSRTitle"
      :unit="waterLSRUnit"
      :data="waterLSRData"
    />
    <!-- <fabBoardEchartsModelBoxItem ref="waterPressureRef" exportImage :title="waterPressureTitle" :data="waterPressureData" /> -->
    <fabBoardEchartsModelBoxItem
      ref="waterEffluentRef"
      exportImage
      exportData
      echartsType="line-water"
      :title="waterEffluentTitle"
      :data="waterEffluentData"
      :unit="waterEffluentUnit"
      @exportDataChange="exportDataHandler"
    >
      <template #headRight>
        <px-select v-model="effluent" style="width: 120px" size="small" placeholder="请选择废液类型" @change="effluentChangeHandler">
          <px-option v-for="item in effluentOptions" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </template>
    </fabBoardEchartsModelBoxItem>
  </div>
</template>

<style lang="scss" scoped>
.water-content {
  display: grid;
  grid-template-rows: repeat(1, v-bind(module_height));
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  width: 100%;
  // height: 100%;
}
</style>
